#!/bin/bash

# shellcheck disable=SC1091
. ../../lib/shflags

PASS=$(cat /proc/sys/kernel/random/uuid)
echo "Generated Password: $PASS"
echo "Generated Password: $PASS" > password.txt

DEFINE_string "password" "$PASS" 'root password' 'p'
DEFINE_integer "expose" 3306 'expose port' 'e'
DEFINE_string "version" '8.0' 'mysql version' 'v'
DEFINE_boolean "general" false 'enable general log' 'l'

# 解析命令行参数
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

echo "password, ${FLAGS_password}! expose ${FLAGS_expose} version ${FLAGS_version} ."

echo "stop container"
docker stop db && docker rm db

echo "rebuild..."
mkdir -p ~/mysql/data
mkdir -p ~/mysql/conf.d
mkdir -p ~/mysql/backup
mkdir -p ~/mysql/log


cat >~/mysql/my.cnf <<EOF
# Default MySQL server config
[mysqld]
# allow connections from any
bind-address = 0.0.0.0
general_log = 1
general_log_file = /var/log/mysql/general_log.log  # 可选，指定日志文件路径
log_output = FILE  # 或 TABLE，根据需要选择
# 备份密码
[mysqldump]
user=root
password=${FLAGS_password}
EOF

echo "install mysql client"
sudo yum install mysql

# 如果要安装 5.7 则将 mysql:8.0 => mysql:5.7.44 即可。
echo "start container"
docker run --restart=always --privileged=true -d \
    -v ~/mysql/data/:/var/lib/mysql \
    -v ~/mysql/conf.d:/etc/mysql/conf.d \
    -v ~/mysql/my.cnf:/etc/mysql/my.cnf \
    -v ~/mysql/log:/var/log/mysql \
    -p "${FLAGS_expose}":3306 \
    --name db \
    -e MYSQL_ROOT_PASSWORD="${FLAGS_password}" mysql:"${FLAGS_version}"
